#include <QtGui>
#include "tabcreatordialog.h"

const int POS_X = 40;
const int POS_Y = 280;
const int LABEL_HEIGHT = 100;
const int LABEL_WIDTH = 8;
const QString EMPTY_CHORD = "-\n-\n-\n-\n-\n-\n";
const QString TAB_LINE_START = "e|--\nB|--\nG|--\nD|--\nA|--\nE|--\n";
const QString TAB_LINE_END = "-|\n-|\n-|\n-|\n-|\n-|\n";

ChordGroup _chordGroups[7];
QFont _font;
int _index;
int _multi;

TabCreatorDialog::TabCreatorDialog(QWidget *parent) : QDialog(parent)
{
    setupUi(this);

    _emptySpacesLabel->setNum(_emptySpacesSlider->value());
    CreateChordGroups();
    this->FillChordsMainList();

    clearTab();
    LoadFile("chords.txt", true);

    connect(_emptySpacesSlider, SIGNAL(valueChanged(int)), _emptySpacesLabel, SLOT(setNum(int)));
    connect(_chordsMainList, SIGNAL(currentRowChanged(int)), this, SLOT(fillSubList(int)));
    connect(_chordsMainList, SIGNAL(currentRowChanged(int)), _tabPreviewLabel, SLOT(clear()));
    connect(_addChordButton, SIGNAL(clicked()), this, SLOT(insertChord()));
    connect(_newButton, SIGNAL(clicked()), this, SLOT(clearTab()));
    connect(_chordsSubList, SIGNAL(currentRowChanged(int)), this, SLOT(displayPreview(int)));
//    connect(_openButton, SIGNAL(clicked()), this, SLOT(loadTabFile()));
//    connect(_saveButton, SIGNAL(clicked()), this, SLOT(saveTabFile()));
    connect(_newLineButton, SIGNAL(clicked()), this, SLOT(insertNewLine()));
}

void TabCreatorDialog::FillChordsMainList()
{
    char chordname = 'A';
    QString chordString = "";

    for(int i = 0; i < 7; ++i)
    {
        chordString = chordname;
        new QListWidgetItem(chordString, _chordsMainList);

        chordname++;
    }
}

void TabCreatorDialog::NewLine()
{
    int labelPosY = _tabLabels[_tabLabels.count() - 1]->pos().y();
    QLabel *tabEndLabel = new QLabel(TAB_LINE_END, this);
    tabEndLabel->setGeometry((POS_X + LABEL_WIDTH * (_tabLabels.count() - _multi) + 20), labelPosY, LABEL_WIDTH + 10, LABEL_HEIGHT);
    tabEndLabel->setFont(_font);
    tabEndLabel->show();
    _tabLabels.append(tabEndLabel);

    QLabel *newStartLabel = new QLabel(TAB_LINE_START, this);
    newStartLabel->setGeometry(POS_X, labelPosY + LABEL_HEIGHT + 5, LABEL_WIDTH + 20, LABEL_HEIGHT);
    newStartLabel->setFont(_font);
    newStartLabel->show();
    _tabLabels.append(newStartLabel);

    _index += (LABEL_HEIGHT + 5);
    _multi = _tabLabels.count() - 1;
}

void TabCreatorDialog::insertNewLine()
{
    this->NewLine();
}

void TabCreatorDialog::fillSubList(int index)
{
    string str = "";

    _chordsSubList->clear();

    for(int i = 0; i < _chordGroups[index].m_chordGroup.length(); ++i)
    {
        str = _chordGroups[index].m_chordGroup[i].GetChordName();
        new QListWidgetItem(QString(str.c_str()), _chordsSubList);
    }
}

void TabCreatorDialog::insertChord()
{
    if(_chordsSubList->currentRow() < 0)
        return;

    addChord(_chordGroups[_chordsMainList->currentRow()].m_chordGroup[_chordsSubList->currentRow()].GetChordColumn());
}

void TabCreatorDialog::addChord(string chordColumn)
{
    if(_tabLabels[_tabLabels.count() - 1]->x() >= 636) // 636 = posX of the last chord
    {
       NewLine();
    }

    int multi = _tabLabels.count() - _multi;
    QString labelText = "";

    for(int i = 0; i < 6; ++i)
    {
        labelText += chordColumn[i];
        labelText += '\n';
    }

    QLabel *label = new QLabel(labelText, this);
    label->setFont(_font);
    label->setGeometry((POS_X + LABEL_WIDTH * (multi) + 20), POS_Y + _index, LABEL_WIDTH, LABEL_HEIGHT);
    label->show();
    _tabLabels.append(label);

    if(_emptySpacesSlider->value() > 0)
    {
        for(int j = 0;  j < _emptySpacesSlider->value(); ++j)
        {
            QLabel *emptyLabel = new QLabel(EMPTY_CHORD, this);
            emptyLabel->setFont(_font);
            emptyLabel->setGeometry((POS_X + LABEL_WIDTH * (multi + j + 1) + 20), POS_Y + _index, LABEL_WIDTH, LABEL_HEIGHT);
            emptyLabel->show();
            _tabLabels.append(emptyLabel);
        }
    }
}

void TabCreatorDialog::clearTab()
{
    // destroy all tab-related labels
    for(int i = 0; i < _tabLabels.count(); ++i)
    {
        _tabLabels[i]->~QWidget();
    }

    _tabLabels.clear();

    _tabStartLabel = new QLabel(TAB_LINE_START, this);
    _tabStartLabel->setGeometry(POS_X, POS_Y, LABEL_WIDTH + 20, LABEL_HEIGHT);

    _font.setFamily(QString::fromUtf8("Courier New"));
    _tabStartLabel->setFont(_font);
    _tabStartLabel->show();
    _tabLabels << _tabStartLabel;

    _index = 0;
    _multi = 0;

}

void TabCreatorDialog::displayPreview(int index)
{
    if(index < 0)
        return;

    QString str(_chordGroups[_chordsMainList->currentRow()].m_chordGroup[index].GetChordPreview().c_str());
    _tabPreviewLabel->setText(str);
}

void TabCreatorDialog::loadTabFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Tab"), "", tr("Tab Files (*.txt)"));

    parseTextFile(LoadFile(fileName, false));
}

void TabCreatorDialog::saveTabFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Tab As..."), "", tr("Tab Files (*.txt)"));
    QString content = ConvertLabelsToText();

    if(!fileName.contains(".txt"))
        fileName += ".txt";

    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    file.write(content.toAscii());

    file.close();
}

QString TabCreatorDialog::ConvertLabelsToText()
{
    QString tab = "";

    return tab;
}

void TabCreatorDialog::parseTextFile(string textFile)
{

}

void CreateChordGroups()
{
    char cgn = 'A';

    for(int i = 0; i < 7; ++i)
    {
        _chordGroups[i].SetChordGroupName(cgn);
        cgn++;
    }
}

string LoadFile(QString fileName, bool isChordFile)
{
    string textFile = "";
    QByteArray arr;

    QFile file(fileName);
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
        return "";

    QTextStream text(&file);

    if(!isChordFile)
    {
        arr = file.readAll();

        textFile = arr.constData();
    }
    else
    {
        while(!text.atEnd())
        {
            textFile = text.readLine().toStdString();
            FillChordsLists(textFile);
        }
        textFile = "";
    }

    return textFile;
}

void FillChordsLists(string chordLine)
{
    if(chordLine == "")
        return;

    string chordName = "";
    string chordColumn = "";
    int len = chordLine.length();

    for(int i = 0; i < len; ++i)
    {
        if(chordLine[i] == '$')
            break;

        chordName += chordLine[i];
    }

    chordColumn = chordLine.substr(len - 6, len);
    Chord *chord = new Chord(chordName, chordColumn);

    _chordGroups[chordLine[0] - 65].m_chordGroup << *chord;
}
